import { Component } from '@angular/core';
import { AbstractControl, FormControl, FormGroup } from '@angular/forms';
import { FormlyFieldConfig } from '@ngx-formly/core';
import { Observable } from 'rxjs';
import { ApesField } from './apes-field';
import { ApiService } from '@core/services/http/api.service';
import { Events } from '@core/services/events/Events';
import { ExpressionService } from '@core/services/expression/ExpressionService';
import { SubjectService } from '@core/services/events/subject.service';

@Component({
  selector: 'formly-field-multicheckbox',
  template: `
    <label apes-checkbox
           *ngFor="let option of to.options;"
           [formControl]="formControl.get(option.key)"
           [formlyAttributes]="field">
      <span [title]="option.label">{{ option.label }}</span>
    </label>
  `,
})

export class FormlyFieldMultiCheckbox extends ApesField {
  constructor(protected apiService: ApiService, protected events: Events, protected expressionService: ExpressionService, protected subject: SubjectService) {
    super(apiService, events, expressionService, subject);
  }

  static createControl(model: any, field: FormlyFieldConfig): AbstractControl {
    if (!(field.templateOptions.options instanceof Observable)) {
      const controlGroupConfig = field.templateOptions.options.reduce((previous, option) => {
        previous[option.key] = new FormControl(model ? model[option.key] : undefined);
        return previous;
      }, {});

      return new FormGroup(
        controlGroupConfig,
        field.validators ? field.validators.validation : undefined,
        field.asyncValidators ? field.asyncValidators.validation : undefined,
      );
    } else {
      throw new Error(`[Formly Error] You cannot pass an Observable to a multicheckbox yet.`);
    }
  }
}
